<template>
  <div class="sheep-purchase-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/OnePages' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>羊场业务</el-breadcrumb-item>
      <el-breadcrumb-item>羊只采购</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="title">羊只采购</h1>
      <p class="subtitle">记录和管理羊只采购信息</p>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" size="default" @click="addNewRecord" :icon="Plus" class="btn-primary">新增</el-button>
      <el-button type="success" size="default" @click="saveRecords" :icon="Check" class="btn-success">保存</el-button>
      <el-button size="default" @click="resetForm" :icon="RefreshRight" class="btn-reset">撤销</el-button>
      <el-button type="danger" size="default" @click="deleteSelected" :icon="Delete" class="btn-delete">删除</el-button>
    </div>

    <!-- 采购基本信息卡片 -->
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">采购基本信息</h3>
      </div>
      <div class="card-body">
        <el-form :model="purchaseInfo" label-width="120px" class="purchase-form">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="采购员" class="form-item">
                <el-input v-model="purchaseInfo.purchaser" placeholder="请输入采购员" class="form-input" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="采购日期" class="form-item">
                <el-date-picker v-model="purchaseInfo.purchaseDate" type="date" placeholder="选择日期" class="form-input"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="羊只类型" class="form-item">
                <el-select v-model="purchaseInfo.sheeptype" placeholder="请选择" class="form-input" clearable>
                  <el-option label="种羊" value="breeder" />
                  <el-option label="肉羊" value="meat" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="供应商" class="form-item">
                <el-input v-model="purchaseInfo.supplier" placeholder="请输入供应商" class="form-input" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="仓库" class="form-item">
                <el-input v-model="purchaseInfo.warehouse" placeholder="请输入仓库" class="form-input" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="类别" class="form-item">
                <el-input v-model="purchaseInfo.category" placeholder="请输入类别" class="form-input" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="核算单元" class="form-item">
                <el-select v-model="purchaseInfo.accountingunit" placeholder="请选择" class="form-input" clearable>
                  <el-option label="单元1" value="unit1" />
                  <el-option label="单元2" value="unit2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="摘要" class="form-item">
                <el-input v-model="purchaseInfo.abstract" placeholder="请输入摘要" class="form-input" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单据号" class="form-item">
                <el-input v-model="purchaseInfo.documentnumber" placeholder="请输入单据号" class="form-input" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="流水号" class="form-item">
                <el-input v-model="purchaseInfo.serialnumber" placeholder="请输入流水号" class="form-input" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <!-- 表格操作区域 -->
    <div class="table-section">
      <div class="section-header">
        <h3 class="section-title">采购明细</h3>
        <div class="table-actions">
          <el-button type="success" plain @click="addRow" :icon="Plus" class="btn-table-action">增行</el-button>
          <el-button type="danger" plain @click="deleteRow" :icon="Delete" class="btn-table-action">删行</el-button>
        </div>
      </div>

      <!-- 编辑表格 -->
      <el-table :data="editingData" border style="width: 100%" class="edit-table"
        :row-style="{ transition: 'all 0.3s' }" v-loading="false">
        <el-table-column prop="index" label="序号" width="60" align="center" />
        <el-table-column prop="earNumber" label="*耳号" width="120">
          <template #default="{ row }">
            <el-input v-model="row.earNumber" placeholder="请输入耳号" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="poultryHouse" label="栋舍" width="120">
          <template #default="{ row }">
            <el-select v-model="row.poultryHouse" placeholder="请选择" class="table-input">
              <el-option label="大羊舍" value="大羊舍" />
              <el-option label="配种舍" value="配种舍" />
              <el-option label="采购羊栋舍" value="采购羊栋舍" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="transferField" label="转场" width="80">
          <template #default="{ row }">
            <el-input-number v-model="row.transferField" :min="0" controls-position="right" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="{ row }">
            <el-select v-model="row.sex" placeholder="请选择" class="table-input">
              <el-option label="公" value="公" />
              <el-option label="母" value="母" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" width="120">
          <template #default="{ row }">
            <el-input v-model="row.productName" placeholder="请输入商品名称" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="label" label="标包" width="80">
          <template #default="{ row }">
            <el-input v-model="row.label" placeholder="请输入标包" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80">
          <template #default="{ row }">
            <el-input v-model="row.unit" placeholder="请输入单位" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="quantityNum" label="数量" width="100">
          <template #default="{ row }">
            <el-input-number v-model="row.quantityNum" :min="0" controls-position="right" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价(元)" width="100">
          <template #default="{ row }">
            <el-input v-model="row.price" placeholder="请输入单价" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额(元)" width="100">
          <template #default="{ row }">
            <el-input v-model="row.amount" placeholder="请输入金额" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="unitDiscount" label="单位折扣" width="100">
          <template #default="{ row }">
            <el-input v-model="row.unitDiscount" placeholder="请输入单位折扣" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="adjustAmount" label="调整金额" width="100">
          <template #default="{ row }">
            <el-input v-model="row.adjustAmount" placeholder="请输入调整金额" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="settlement" label="结算" width="100">
          <template #default="{ row }">
            <el-input v-model="row.settlement" placeholder="请输入结算" class="table-input" />
          </template>
        </el-table-column>
        <el-table-column prop="totalweight" label="总重量(kg)" width="120">
          <template #default="{ row }">
            <el-input-number v-model="row.totalweight" :min="0" :precision="2" controls-position="right" class="table-input" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 操作提示 -->
      <div class="hint" v-if="editingData.length === 0">
        <el-alert title="提示信息" description="点击'增行'按钮添加采购明细数据" type="info" :closable="false" class="info-alert" />
      </div>
    </div>

    <!-- 已保存记录 -->
    <div class="saved-records-section" v-if="savedData.length > 0">
      <h3 class="section-title">已保存记录</h3>
        <el-table :data="savedData" border style="width: 100%" class="saved-table" :row-style="{ transition: 'all 0.3s' }"
        highlight-current-row @row-click="handleRowClick">
        <el-table-column prop="procurementId" label="ID" width="60" align="center" />
        <el-table-column prop="earNumber" label="耳号" width="120" />
        <el-table-column prop="poultryHouse" label="栋舍" width="120" />
        <el-table-column prop="transferField" label="转场" width="80" align="center" />
        <el-table-column prop="sex" label="性别" width="80" align="center" />
        <el-table-column prop="productName" label="商品名称" width="120" />
        <el-table-column prop="label" label="标包" width="80" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="quantityNum" label="数量" width="100" align="center" />
        <el-table-column prop="price" label="单价(元)" width="100" align="center" />
        <el-table-column prop="amount" label="金额(元)" width="100" align="center" />
        <el-table-column prop="totalweight" label="总重量(kg)" width="120" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="editRecord(row)" :icon="Edit" class="edit-link">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Check, RefreshRight, Delete, Edit } from '@element-plus/icons-vue'
import axios from 'axios'

interface ProcurementRecord {
  procurementId: number
  earNumber: string
  poultryHouse: string
  transferField: number
  sex: string
  productName: string
  label: string
  unit: string
  quantityNum: number
  price: string
  amount: string
  unitDiscount: string
  adjustAmount: string
  settlement: string
  totalweight: number
  isDeleted: boolean
}

interface PurchaseInfo {
  purchaser: string
  purchaseDate: string
  sheeptype: string
  category: string
  accountingunit: string
  supplier: string
  warehouse: string
  abstract: string
  documentnumber: string
  serialnumber: string
}

const purchaseInfo = reactive<PurchaseInfo>({
  purchaser: '',
  purchaseDate: '',
  sheeptype: '',
  category: '',
  accountingunit: '',
  supplier: '',
  warehouse: '',
  abstract: '',
  documentnumber: '',
  serialnumber: ''
})

const editingData = ref<ProcurementRecord[]>([])
const savedData = ref<ProcurementRecord[]>([])
let recordIndex = 1

const addNewRecord = () => {
  editingData.value = []
  addRow()
}

const addRow = () => {
  editingData.value.push({
    procurementId: 0,
    earNumber: '',
    poultryHouse: '',
    transferField: 0,
    sex: '',
    productName: '',
    label: '',
    unit: '',
    quantityNum: 0,
    price: '',
    amount: '',
    unitDiscount: '',
    adjustAmount: '',
    settlement: '',
    totalweight: 0,
    isDeleted: false
  })
}

const deleteRow = () => {
  if (editingData.value.length > 0) {
    editingData.value.pop()
    if (editingData.value.length === 0) {
      recordIndex = 1
    }
  }
}

const saveRecords = async () => {
  try {
    // 验证表单数据
    if (!purchaseInfo.purchaser) {
      ElMessage.warning('请输入采购员')
      return
    }
    if (!purchaseInfo.purchaseDate) {
      ElMessage.warning('请选择采购日期')
      return
    }
    if (!purchaseInfo.supplier) {
      ElMessage.warning('请输入供应商')
      return
    }

    // 校验表格数据
    if (!editingData.value || editingData.value.length === 0) {
      ElMessage.warning('请至少添加一条采购明细')
      return
    }

    // 过滤有效数据
    const validRecords = editingData.value.filter(record =>
      record.earNumber || record.poultryHouse || record.productName || record.sex
    )

    if (validRecords.length === 0) {
      ElMessage.warning('请至少填写一条完整的采购明细')
      return
    }

    // 格式化日期为ISO格式
    let formattedDate = ''
    if (purchaseInfo.purchaseDate) {
      // 检查是否是字符串类型
      if (typeof purchaseInfo.purchaseDate === 'string') {
        // 如果已经是ISO格式，直接使用
        if (purchaseInfo.purchaseDate.includes('T')) {
          formattedDate = purchaseInfo.purchaseDate
        } else {
          // 如果不是ISO格式，转换为ISO格式
          formattedDate = new Date(purchaseInfo.purchaseDate).toISOString()
        }
      } else {
        // 如果是Date对象或其他类型，转换为ISO格式
        formattedDate = new Date(purchaseInfo.purchaseDate).toISOString()
      }
    }

    // 构建API请求数据
    const apiPayload = {
      purchaser: purchaseInfo.purchaser,
      purchaseDate: formattedDate,
      sheeptype: purchaseInfo.sheeptype,
      category: purchaseInfo.category,
      accountingunit: purchaseInfo.accountingunit,
      supplier: purchaseInfo.supplier,
      warehouse: purchaseInfo.warehouse,
      abstract: purchaseInfo.abstract,
      documentnumber: purchaseInfo.documentnumber,
      serialnumber: purchaseInfo.serialnumber,
      procurementList: validRecords.map(row => ({
        procurementId: row.procurementId,
        earNumber: row.earNumber,
        poultryHouse: row.poultryHouse,
        transferField: row.transferField,
        sex: row.sex,
        productName: row.productName,
        label: row.label,
        unit: row.unit,
        quantityNum: row.quantityNum,
        price: row.price,
        amount: row.amount,
        unitDiscount: row.unitDiscount,
        adjustAmount: row.adjustAmount,
        settlement: row.settlement,
        totalweight: row.totalweight,
        isDeleted: false
      }))
    }

    console.log('发送到后端的数据:', JSON.stringify(apiPayload, null, 2))

    // 使用axios发送请求
    console.log('开始发送请求到:', 'http://localhost:5008/api/Management/CreateProcurement')
    console.log('请求数据:', apiPayload)
    
    const response = await axios.post('http://localhost:5008/api/Management/CreateProcurement', apiPayload, {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      timeout: 10000
    })
    
    console.log('后端响应状态:', response.status)
    console.log('后端响应数据:', response.data)

    if (response.status === 200) {
      if (response.data && (response.data.success === true || response.data.code === 200 || response.data.message === 'success' || response.data.code === 100)) {
        ElMessage.success(`保存成功，共保存${validRecords.length}条记录`)
        
        // 清空表单数据
        Object.assign(purchaseInfo, {
          purchaser: '',
          purchaseDate: '',
          sheeptype: '',
          category: '',
          accountingunit: '',
          supplier: '',
          warehouse: '',
          abstract: '',
          documentnumber: '',
          serialnumber: ''
        })
        
        // 重置表格数据
        editingData.value = []
        recordIndex = 1
      } else {
        console.log('后端返回失败状态:', response.data)
        ElMessage.error(`保存失败: ${response.data?.message || response.data?.msg || '后端返回失败状态'}`)
      }
    } else {
      console.log('HTTP状态码不是200:', response.status)
      ElMessage.error(`保存失败，HTTP状态码: ${response.status}`)
    }
  } catch (error: any) {
    console.log('=== 请求异常详情 ===')
    console.error('保存失败:', error)
    
    if (error.response) {
      console.log('错误响应状态:', error.response.status)
      console.log('错误响应数据:', error.response.data)
      
      if (error.response.status === 400) {
        console.log('400错误详情:', error.response.data)
        if (error.response.data?.errors) {
          const validationErrors = error.response.data.errors
          let errorMessage = '保存失败: 数据验证错误\n'
          for (const field in validationErrors) {
            errorMessage += `${field}: ${validationErrors[field].join(', ')}\n`
          }
          ElMessage.error(errorMessage)
        } else {
          ElMessage.error(`保存失败: 请求参数错误(400) - ${error.response.data?.title || error.response.data?.message || '请检查数据格式'}`)
        }
      } else if (error.response.status === 404) {
        ElMessage.error('保存失败: API接口不存在(404)，请检查后端路由配置')
      } else if (error.response.status === 401) {
        ElMessage.error('保存失败: 未授权(401)，请检查认证信息')
      } else if (error.response.status === 500) {
        ElMessage.error('保存失败: 服务器内部错误(500)')
      } else {
        ElMessage.error(`保存失败: ${error.response.status} - ${error.response.data?.message || error.response.data?.msg || '服务器错误'}`)
      }
    } else if (error.request) {
      console.log('网络请求失败:', error.request)
      ElMessage.error('保存失败: 网络连接异常，请检查后端服务是否启动在端口5008')
    } else if (error.code === 'ECONNABORTED') {
      console.log('请求超时:', error.message)
      ElMessage.error('保存失败: 请求超时，请检查网络连接')
    } else {
      console.log('其他错误:', error.message)
      ElMessage.error(`保存失败: ${error.message}`)
    }
  }
}

const editRecord = (record: ProcurementRecord) => {
  editingData.value = [JSON.parse(JSON.stringify(record))]
}

const resetForm = () => {
  editingData.value = []
  recordIndex = 1
}

const deleteSelected = () => {
  if (savedData.value.length > 0) {
    ElMessageBox.confirm('确定要删除所有已保存的记录吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      savedData.value = []
      ElMessage.success('删除成功')
    }).catch(() => {
      ElMessage.info('已取消删除')
    })
  } else {
    ElMessage.warning('没有可删除的记录')
  }
}

const handleRowClick = (row: ProcurementRecord) => {
  console.log('点击了行:', row)
}
</script>

<style scoped>
/* 全局容器样式 */
.sheep-purchase-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
}

/* 面包屑样式 */
.breadcrumb {
  margin-bottom: 20px;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 28px;
  padding-bottom: 16px;
  border-bottom: 2px solid #409eff;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

/* 操作按钮样式 */
.action-buttons {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.btn-primary,
.btn-success,
.btn-reset,
.btn-delete {
  transition: all 0.3s ease;
}

.btn-primary:hover,
.btn-success:hover,
.btn-reset:hover,
.btn-delete:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 卡片样式 */
.card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.card-header {
  padding: 16px 24px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.card-body {
  padding: 24px;
}

/* 表单样式 */
.purchase-form {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  transition: all 0.3s ease;
}

.form-input:hover {
  border-color: #c0c4cc;
}

.form-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

/* 表格区域样式 */
.table-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  padding: 24px;
  transition: all 0.3s ease;
  overflow-x: auto;
}

.table-section:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.btn-table-action {
  transition: all 0.3s ease;
  border-width: 1px;
}

.btn-table-action:hover {
  transform: translateY(-1px);
}

/* 表格样式 */
.edit-table,
.saved-table {
  border-radius: 4px;
  overflow: hidden;
}

.edit-table .el-table__header-wrapper th,
.saved-table .el-table__header-wrapper th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #303133;
}

.edit-table .el-table__body-wrapper tr:hover,
.saved-table .el-table__body-wrapper tr:hover {
  background-color: #fafafa;
}

.table-input {
  transition: all 0.3s ease;
}

.table-input:hover {
  border-color: #c0c4cc;
}

.table-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

/* 提示信息样式 */
.hint {
  margin-top: 16px;
}

.info-alert {
  border-radius: 4px;
}

/* 已保存记录区域样式 */
.saved-records-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
  transition: all 0.3s ease;
}

.saved-records-section:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.edit-link {
  color: #409eff;
  transition: all 0.3s ease;
}

.edit-link:hover {
  color: #66b1ff;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .sheep-purchase-container {
    padding: 16px;
  }

  .action-buttons {
    justify-content: center;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-body,
  .table-section,
  .saved-records-section {
    padding: 16px;
  }
}
</style>